package cn.stylefeng.guns.sys.modular.system.service;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.ExcelUtil;
import cn.stylefeng.guns.sys.modular.system.entity.BtyBorrower;
import cn.stylefeng.guns.sys.modular.system.entity.BtyBorrowerFlowInformation;
import cn.stylefeng.guns.sys.modular.system.entity.ExcelExp;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyBorrowerFlowInformationMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyBorrowerMapper;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 档案管理表 服务实现类
 * </p>
 *
 * @author liuy
 * @since
 */
@Service
public class BtyBorrowerFlowInformationService extends ServiceImpl<BtyBorrowerFlowInformationMapper, BtyBorrowerFlowInformation> {

    Logger logger = LoggerFactory.getLogger(BtyBorrowerFlowInformationService.class);


    @Autowired
    private BtyBorrowerMapper borrowerMapper;

    /**
     * 获取档案管理列表
     */
    @Resource
    private BtyBorrowerService btyBorrowerService;

    public Page<Map<String, Object>> list(String condition, String month, String status) {
        Page page = LayuiPageFactory.defaultPage();

        return this.baseMapper.list(page, condition, month, status);
    }

    public Page<Map<String, Object>> listSearch(String borrowerId, String beginTime, String endTime) {
        Page page = LayuiPageFactory.defaultPage();

        return this.baseMapper.listSearch(page, borrowerId, beginTime, endTime);
    }

    /**
     * 获取所有未还款金额
     */
    public Double allMoney() {
        return this.baseMapper.allOldMoney() + this.baseMapper.allNewMoney();
    }

    public List<BtyBorrowerFlowInformation> borrowerInfo() {
        return baseMapper.borrowerInfo();
    }

    public List<BtyBorrowerFlowInformation> listByBorrowerId(String borrowerId) {
        return baseMapper.listByBorrowerId(borrowerId);
    }

    public int insertFq(Long id, String borrowerId, String loanDate, String bj, String yll, String month, String hkje, String lx, Date createTime, Long userId, String summary) {
        return baseMapper.insertFq(id, borrowerId, loanDate, bj, yll, month, hkje, lx, createTime, userId, summary);
    }


    public int updateByIds(String[] ids) {
        return baseMapper.updateByIds(ids);
    }

    /**
     * 导入还款金额excel
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Boolean batchImport(String fileName, MultipartFile file) throws Exception {
        boolean notNull = false;
        StringBuilder stringBuilder = new StringBuilder(DateUtil.getLastMonth());
        String lastMonth = stringBuilder.replace(4, 4, "-").toString();
        List<BtyBorrowerFlowInformation> userList = new ArrayList<>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        //excel中多个sheet表，获取所有sheet表的数量
        int sheets = wb.getNumberOfSheets();
        for (int i = 0; i < sheets; i++) {
            Sheet sheet = wb.getSheetAt(i);
            if (sheet != null) {
                notNull = true;
            }
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                //获取单元格
                Cell cell = row.getCell(4);
                if (ToolUtil.isNotEmpty(cell)) {
                    cell.setCellType(CellType.STRING);
                }
                String yhkje = row.getCell(4) == null ? "" : row.getCell(4).getStringCellValue();
                String name = row.getCell(9) == null ? "" : row.getCell(9).getStringCellValue();
                String summary = row.getCell(10) == null ? "" : row.getCell(10).getStringCellValue();
                if (yhkje != null && !"".equals(yhkje) && !"0".equals(yhkje)) {
                    if ("殷世峰".equals(name)) {
                        name = "伦志超";
                    }
                    int a = 0;
                    List<BtyBorrowerFlowInformation> btyBorrowers = this.baseMapper.borrowerInfo();
                    for (int j = 0; j < btyBorrowers.size(); j++) {
                        if (summary.contains("滕艳杰")) {
                            summary = "王雷";
                        }
                        String xm = btyBorrowers.get(j).getName();
                        if (summary.contains(xm)) {
                            a = 1;
                            List<BtyBorrowerFlowInformation> btyBorrowerFlow = this.baseMapper.selectByName(xm, lastMonth);
                            if (btyBorrowerFlow.size() > 0) {
                                selectByName(yhkje, btyBorrowerFlow);
                            }
                        }
                    }
                    if (a == 0) {
                        List<BtyBorrowerFlowInformation> btyBorrower = this.baseMapper.selectByName(name, lastMonth);
                        if (btyBorrower.size() > 0) {
                            selectByName(yhkje, btyBorrower);
                        }
                    }
                }
            }
        }
        return notNull;
    }

    /**
     * 公共方法
     */
    public int selectByName(String yhkje, List<BtyBorrowerFlowInformation> btyBorrower) {
        BigDecimal ayhkje = new BigDecimal(String.format("%.2f", new BigDecimal(yhkje)));
        BigDecimal money = new BigDecimal(String.format("%.2f", new BigDecimal(btyBorrower.get(0).getHkje()).add(new BigDecimal(btyBorrower.get(0).getLx()))));
        MathContext mc = new MathContext(2);
        BigDecimal[] bigDecimals = ayhkje.divideAndRemainder(money, mc);
        int bs = Integer.parseInt(bigDecimals[0].stripTrailingZeros().toPlainString());
        if (bs > 0) {
            int ys = Integer.parseInt(bigDecimals[1].toPlainString().substring(0, bigDecimals[1].toPlainString().indexOf(".")));
            if (ys == 0 || ys < 1) {
                BtyBorrowerFlowInformation btyBorrow = new BtyBorrowerFlowInformation();
                btyBorrow.setId(btyBorrower.get(0).getId());
                btyBorrow.setYhkje(money.toString());
                btyBorrow.setFlag(1);
                this.baseMapper.updateYhkjes(btyBorrow);
            }
        } else if (btyBorrower.size() > 0) {
            BigDecimal moneyAmount = new BigDecimal(0);
            for (int j = 0; j < btyBorrower.size(); j++) {
                moneyAmount = new BigDecimal(btyBorrower.get(j).getLx()).add(new BigDecimal(btyBorrower.get(j).getHkje())).add(moneyAmount);
            }
            if (ayhkje.compareTo(moneyAmount) >= 0) {
                for (int k = 0; k < btyBorrower.size(); k++) {
                    BtyBorrowerFlowInformation btyBorrow = new BtyBorrowerFlowInformation();
                    btyBorrow.setId(btyBorrower.get(k).getId());
                    btyBorrow.setYhkje(new BigDecimal(btyBorrower.get(k).getLx()).add(new BigDecimal(btyBorrower.get(k).getHkje())).toString());
                    btyBorrow.setFlag(1);
                    this.baseMapper.updateYhkjes(btyBorrow);
                }
            }
        }
        return 1;
    }

    /**
     * 批量导出excel
     *
     * @param request
     * @param response
     * @param borrowerId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, String borrowerId) {
        //设置日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String number = sdf.format(new Date());
        DecimalFormat format = new DecimalFormat("0.00");
        // 查询数据
        List<BtyBorrowerFlowInformation> btyBorrowerFlowInformationList;
        List<BtyBorrower> btyBorrowerList;

        String fileName = number + "借贷款流水导出";
        String path = "D:\\" + "xls\\";
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs(); //创建目录
        }
        String url = path + fileName + ".xls";
        System.out.println("url:" + url);
        try {

            //查询所有的要导出的数据
            btyBorrowerFlowInformationList = this.baseMapper.listExport(borrowerId);

            //查询所有的借款人列表
            btyBorrowerList = borrowerMapper.nameList();

            List<ExcelExp> mysheet = new ArrayList<>();

            if (btyBorrowerList != null && btyBorrowerList.size() > 0) {
                //循环借款人
                for (BtyBorrower btyBorrower : btyBorrowerList) {

                    List<BtyBorrowerFlowInformation> list = new ArrayList<>();
                    List<String[]> datasetList = new ArrayList<>();

                    if (btyBorrowerFlowInformationList != null && btyBorrowerFlowInformationList.size() > 0) {
                        //循环数据
                        for (BtyBorrowerFlowInformation btyBorrowerFlowInformation : btyBorrowerFlowInformationList) {
                            if (btyBorrower.getId().toString().equals(btyBorrowerFlowInformation.getBorrowerId())) {

                                list.add(btyBorrowerFlowInformation);

                            }
                        }
                    }

                    for (int i = 0; i < list.size(); i++) {
                        String[] arr = new String[13];
                        arr[0] = list.get(i).getLoanDate() == null ? "" : list.get(i).getLoanDate();//日期
                        arr[1] = list.get(i).getName() == null ? "" : list.get(i).getName();//姓名
                        arr[2] = list.get(i).getSummary() == null ? "" : list.get(i).getSummary();//摘要
                        arr[3] = list.get(i).getDebit() == null ? "" : list.get(i).getDebit();//借方
                        arr[4] = list.get(i).getCredit() == null ? "" : list.get(i).getCredit();//贷方
                        arr[5] = list.get(i).getBalance() == null ? "" : list.get(i).getBalance();//余额
                        arr[6] = list.get(i).getBj() == null ? "" : list.get(i).getBj();//借款本金
                        arr[7] = list.get(i).getYll() == null ? "" : list.get(i).getYll();//月利率
                        arr[8] = list.get(i).getMonth() == null ? "" : list.get(i).getMonth();//还款月份
                        arr[9] = list.get(i).getHkje() == null ? "" : list.get(i).getHkje();//应还款本金
                        arr[10] = list.get(i).getLx() == null ? "" : list.get(i).getLx();//应还款利息
                        arr[11] = list.get(i).getYhkje() == null ? "" : list.get(i).getYhkje();//已还款金额
                        arr[12] = list.get(i).getRemark() == null ? "" : list.get(i).getRemark();//备注
                        datasetList.add(arr);
                    }

                    //表头
                    String[] handers = {"日期", "姓名", "摘要", "借方", "贷方", "余额", "借款本金", "月利率", "还款月份", "应还款本金", "应还款利息", "已还款金额", "备注"};

                    //对象
                    ExcelExp hp = new ExcelExp(btyBorrower.getName(), handers, datasetList);

                    mysheet.add(hp);

                }
            }

            //生成sheet
            ExcelUtil.exportManySheetExcel(url, mysheet);
            //下载sheet
            ExcelUtil.getExcel(url, fileName, response);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
